package com.yonyou.eco.taxclouddemo.controller;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.eco.taxclouddemo.constant.WeChatConstant;
import com.yonyou.eco.taxclouddemo.utils.HttpClientUtil;
import com.yonyou.eco.taxclouddemo.utils.Sha1Util;
import com.yonyou.eco.taxclouddemo.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.UUID;

/**
 * @Description: 企业微信对接个人票夹相关接口
 * @Author: jiaogjin
 * @Date: 2022/5/26 16:05
 */
@RestController
@Slf4j
public class EnterpriseWechatPiaoedaController {

    /**
     * 功能描述: 接口一（获取用户信息）
     * @Author: jiaogjin
     * @Date: 2022/5/27 9:41
     */
    @GetMapping("/userinfo")
    public Result userinfo(@RequestParam String appid,
                           @RequestParam String code,
                           @RequestParam String ts,
                           @RequestParam String sign) throws Exception {
        log.info("请求参数为:appid="+appid+";code="+code+";ts="+ts+";sign="+sign);
        Result result = new Result();
        //测试代码，省略了验签功能(根据文档《企业微信对接接口设计.pdf》中签名说明提供的验签方式验证即可)，参考类本项目中的SignUtils
        //获取access_token
        Result tokenResult =  getToken(appid);
        if(("0001").equals(tokenResult.getCode())){
            return tokenResult;
        }
        //根据code获取成员信息
        HashMap<String,Object> uerReqMap = new HashMap<String, Object>();
        uerReqMap.put("access_token",tokenResult.getDatas());
        uerReqMap.put("code",code);
        String userinfoRes = HttpClientUtil.getNoSign(WeChatConstant.GETUSERINFO,uerReqMap);
        log.info("userinfoRes="+userinfoRes);
        JSONObject userinfoJson = JSONObject.parseObject(userinfoRes);
        if(0!=userinfoJson.getInteger("errcode")){
            result.setCode("0002");
            result.setMsg("获取用户信息失败");
            return result;
        }
        //读取成员信息
        HashMap<String,Object> reqMap = new HashMap<String, Object>();
        reqMap.put("access_token",tokenResult.getDatas());
        reqMap.put("userid",userinfoJson.getString("UserId"));
        String userRes = HttpClientUtil.getNoSign(WeChatConstant.GETUSER,reqMap);
        log.info("userRes="+userRes);
        JSONObject userJson = JSONObject.parseObject(userRes);
        if(0!=userJson.getInteger("errcode")){
            result.setCode("0003");
            result.setMsg("获取成员信息失败");
            return result;
        }
        //封装返回信息
        result.setCode("0000");
        result.setMsg("操作成功");
        HashMap<String,Object> map = new HashMap<String, Object>();
        map.put("email",userJson.getString("email"));
        map.put("mobile",userJson.getString("mobile"));
        map.put("name",userJson.getString("name"));
        result.setDatas(map);
        log.info("返回信息："+JSONObject.toJSONString(result));
        return result;
    }

    /**
     * 功能描述: 接口二（获取JS_SDK初始化参数）
     * @Author: jiaogjin
     * @Date: 2022/5/27 9:41
     */
    @GetMapping("/js-sdk")
    public Result jsSdk(@RequestParam String sign,
                        @RequestParam String appid,
                        @RequestParam String pageUrl,
                        @RequestParam String ts) throws Exception {
        log.info("请求参数为:sign="+sign+";appid="+appid+";pageUrl="+pageUrl+";ts="+ts);
        Result result = new Result();
        //测试代码，省略了验签功能(根据文档《企业微信对接个人票夹技术方案.word》中签名说明提供的验签方式验证即可)。参考类本项目中的SignUtils
        //获取access_token
        Result tokenResult =  getToken(appid);
        if(("0001").equals(tokenResult.getCode())){
            return tokenResult;
        }
        //获取企业的jsapi_ticket
        HashMap<String,Object> jsTicketReqMap = new HashMap<String, Object>();
        jsTicketReqMap.put("access_token",tokenResult.getDatas());
        String jsapiTicketRes = HttpClientUtil.getNoSign(WeChatConstant.GET_JSAPI_TICKET,jsTicketReqMap);
        log.info("jsapiTicketRes="+jsapiTicketRes);
        JSONObject jsapiTicketJson = JSONObject.parseObject(jsapiTicketRes);
        if(0!=jsapiTicketJson.getInteger("errcode")){
            result.setCode("0002");
            result.setMsg("获取jsapi_ticket信息失败");
            return result;
        }
        String jsapiTicket = jsapiTicketJson.getString("ticket");
        long timestamp = System.currentTimeMillis()/1000;
        String nonceStr = UUID.randomUUID().toString().trim().replaceAll("-","");
        //生成签名（有两个注意点：1. 字段值采用原始值，不要进行URL转义；2. 必须严格按照如下格式拼接，不可变动字段顺序。）
        LinkedHashMap<String, Object> signParams = new LinkedHashMap<String, Object>();
        signParams.put("jsapi_ticket",jsapiTicket);
        signParams.put("noncestr",nonceStr);//随机字符串,但必须与wx.config中的nonceStr相同
        signParams.put("timestamp",timestamp);//时间戳，但必须与wx.config中的timestamp相同,微信文档中该属性类型为long
        signParams.put("url", URLDecoder.decode(pageUrl, "UTF-8"));//签名用的url必须是调用JS接口页面的完整URL
        String signature = Sha1Util.createSHA1Sign(signParams);
        //封装返回信息
        result.setCode("0000");
        result.setMsg("操作成功");
        HashMap<String,Object> map = new HashMap<String, Object>();
        map.put("appid",appid);
        map.put("timestamp",timestamp);
        map.put("nonceStr",nonceStr );
        map.put("signature",signature);
        result.setDatas(map);
        log.info("返回信息："+JSONObject.toJSONString(result));
        return result;
    }

    /**
     * 功能描述: 获取token
     * @Author: jiaogjin
     * @Date: 2022/5/27 10:15
     */
    private Result getToken(String appid) throws Exception {
        Result result = new Result();
        HashMap<String,Object> tokenReqMap = new HashMap<String, Object>();
        tokenReqMap.put("corpid",appid);
        tokenReqMap.put("corpsecret", WeChatConstant.CORPSECRET);
        String tokenRes = HttpClientUtil.getNoSign(WeChatConstant.GETTOKEN,tokenReqMap);
        log.info("tokenRes="+tokenRes);
        JSONObject tokenJson = JSONObject.parseObject(tokenRes);
        if(0!=tokenJson.getInteger("errcode")){
            result.setCode("0001");
            result.setMsg("获取token失败");
            return result;
        }
        result.setCode("0000");
        result.setMsg("获取token成功");
        result.setDatas(tokenJson.getString("access_token"));
        return result;
    }
}
